import axios from "@/router/axios";
import { getRoleCode } from "@/util/business-util";
import { getToken } from "@/util/auth";

// 根据待办类型获取待办已完成/未完成的数量
export let getTodoTotalByType = async function(type, userInfo, conditionOp) {
  let qtyUrl = ""; // 获取未完成/已完成数量的url
  let qtyUrl2 = "";
  let params = getParmas(type, conditionOp); // 获取通用参数
  params["tenantId"] = params.tenantId || userInfo.tenantId;
  let undoneKey = ""; // 未完成key
  let doneKey = ""; // 已完成key
  switch (type) {
    case "evaluation": // '学生测评'
      let roleCode = getRoleCode(userInfo);
      // 学生或者家长
      if (roleCode === "student" || roleCode === "parent") {
        qtyUrl =
          "/api/blade-measure/measure/projectgaugeincludeuser/findEvaluationTotal";
        undoneKey = "wcTotal";
        doneKey = "ycTotal";
      } else {
        // 老师
        qtyUrl = "/api/blade-measure/measure/usersummary/findAllTestGroupTotal";
        undoneKey = "noTestSum";
        doneKey = "testSum";
      }
      break;
    case "warn": // '学生预警'
      qtyUrl = "/api/blade-measure/measure/report/findUserWarnTotal";
      undoneKey = "wcl";
      doneKey = "ycl";
      break;
    // case "reserve": // '学生预约'
    //   qtyUrl = "/api/blade-measure/measure/report/findUserWarnTotal"; // ---------------测试数据---------------------------------
    //   break;
  }
  let { data } = await axios({
    url: qtyUrl,
    method: "get",
    params
  });

  return {
    undoneQty: data.success ? data.data[undoneKey] || 0 : 0, // 未完成的数量
    doneQty: data.success ? data.data[doneKey] || 0 : 0 // 已完成的数量
  };
};

// 根据待办类型获取待办详情
export let getTodoDetails = async function(
  userInfo,
  type,
  conditionOp,
  doneType,
  pager
) {
  let params = getParmas(type, conditionOp); // 获取通用参数
  let url = ""; // 获取详细信息的url
  switch (type) {
    case "evaluation": // '学生测评'
      url =
        "/api/blade-measure/measure/projectgaugeincludeuser/findProjectGaugeIncludeUserPage";
      params.testFlag = doneType === "done" ? "Y" : "N"; // 是否查询已完成的数据
      break;
    case "warn": // '学生预警'
      params.interveneFlag = doneType === "done" ? "Y" : "N"; // 是否查询已完成的数据
      url = "/api/blade-measure/measure/report/findUserWarnList";
      break;
    case "reserve": // '学生预约'
      url = "/api/blade-measure/measure/report/findUserWarnList"; // ---------------测试数据---------------------------------
      break;
  }
  let { data } = await axios({
    url: url,
    method: "get",
    params: {
      tenantId: params.tenantId || userInfo.tenantId,
      ...params,
      current: pager.currentPage,
      size: pager.pageSize
    }
  });
  console.log(params);
  return {
    data: data.success ? data.data.records || [] : [],
    total: data.success ? data.data.total : 0
  };
};
// 待办导出
export let handleExport = function (userInfo, type, conditionOp, doneType) {
  let params = getParmas(type, conditionOp); // 获取通用参数
  let url = ""; // 获取详细信息的url
  switch (type) {
    case "evaluation": // '学生测评'
      url = "/api/blade-measure/measure/projectgaugeincludeuser/export-evaluation-user";
      params.testFlag = doneType === "done" ? "Y" : "N"; // 是否查询已完成的数据
      break;
    case "warn": // '学生预警'
      params.interveneFlag = doneType === "done" ? "Y" : "N"; // 是否查询已完成的数据
      url = "/api/blade-measure/measure/report/export-warn-user";
      break;
  }
  let paramsStr = ''
  let jsonP = Object.assign({}, params, {tenantId: params.tenantId || userInfo.tenantId, current: 1, size: 99999999})
  Object.keys(jsonP).forEach(key => {
    paramsStr += `&${key}=${jsonP[key]}`
  })
  let exportFullUrl = `${url}?blade-auth=${getToken()}${paramsStr}`
  console.log('待办导出url与参数：', url, paramsStr)
  window.open(exportFullUrl)
}
// 获取参数
function getParmas(type, curConditions) {
  let params = Object.assign({}, curConditions || {}); // 参数
  switch (type) {
    case "evaluation": // '学生测评'
      params["userName"] = params["name"];
      params["includeName"] = params["name"];
      break;
    case "warn": // '学生预警'
      params["userName"] = params["name"];
      params["includeName"] = params["name"];
      params.levelFlag = "Y";
      break;
    case "reserve": // '学生预约'
      break;
  }
  delete params["name"];
  return params;
}

// 根据角色、类型获取对应的显示字段
export let getColumns = function(
  userInfo, // 当前用户信息
  activeNames,
  type,
  defaultValue = {}
) {
  if (!userInfo) {
    return [];
  }
  let roleCode = getRoleCode(userInfo);
  let classCode;
  if (activeNames === "evaluation") {
    classCode = "evaluation";
  } else if (activeNames === "warn") {
    classCode = "warn";
  } else if (activeNames === "reserve") {
    classCode = "reserve";
  } else {
    // 其他
    classCode = "other";
  }
  let arr = getColumnsByCond(roleCode, classCode, type, defaultValue);
  return arr.concat(getColumnsByRoleAndType(roleCode, classCode, type));
};

// 获取字段/搜索条件的配置
export const getColumnsByCond = function(
  curRoleCode,
  classCode,
  doneType,
  defaultValue
) {
  let columnArr = [
    {
      label: "学号",
      prop: "userCode",
      search: false
    },
    {
      label: "姓名",
      prop: classCode === "evaluation" ? "includeName" : "userName",
      search: false
    },
    {
      label: "年度",
      prop: "yearly",
      search: curRoleCode === "student" || curRoleCode === "parent" ? false : true,
      searchValue: defaultValue.yearly || "",
      searchLabelWidth: 120,
      searchSpan: 8,
      overHidden: true,
      type: "select",
      props: {
        label: "yearly",
        value: "yearly",
      },
      dicUrl: "/api/blade-measure/measure/term/listAll",
    },
    {
      label: "学期",
      prop: "term",
      search: curRoleCode === "student" || curRoleCode === "parent" ? false : true,
      searchValue: defaultValue.term || "",
      // searchLabelWidth: 130,
      searchSpan: 8,
      overHidden: true,
      type: "select",
      props: {
        label: "term",
        value: "term",
      },
      dicUrl: "/api/blade-measure/measure/term/listAll",
    },
    {
      label: "年级",
      type: "select",
      prop: "gradeName",
      dicUrl: `/api/blade-system/grade/list`,
      props: {
        label: "gradeName",
        value: "gradeName"
      },
      searchValue: defaultValue.gradeName || "",
      // searchLabelWidth: 130,
      searchSpan: 8,
      // slot: true,
      search:
        curRoleCode === "student" || curRoleCode === "parent" ? false : true
    },
    {
      label: "班级",
      prop: "className",
      search: false
    },
    {
      label: "是否专项测试",
      prop: "specialTypeId",
      type: "select",
      // dataType: "number",
      dicData: [
        {
          label: "是",
          value: '1',
        },
        {
          label: "否",
          value: '0',
        },
      ],
      searchValue: defaultValue.specialTypeId || "",
      searchLabelWidth: 120,
      searchSpan: 8,
      // slot: true,
      search:
        curRoleCode === "student" || curRoleCode === "parent" ? false : true
    },
  ];
  // 预警
  if (classCode === "warn") {
    columnArr.push({
      label: "预警等级",
      type: "select",
      prop: "level",
      dicUrl: "/api/blade-system/dict/dictionary?code=warning_level",
      props: {
        label: "dictValue",
        value: "dictKey"
      },
      // slot: true,
      search: false
    });
    // 已完成
    if (doneType === "done") {
      columnArr.push({
        label: "老师建议等级",
        type: "select",
        prop: "personalLevel",
        dicUrl: "/api/blade-system/dict/dictionary?code=warning_level",
        props: {
          label: "dictValue",
          value: "dictKey"
        },
        search: false
      });
      columnArr.push({
        label: "完成日期",
        prop: "updateAt",
        search: false
      });
    }
  }

  return columnArr;
};

// 获取字段配置
function getColumnsByRoleAndType(roleCode, classCode, type) {
  let data = [
    {
      columnOp: { prop: "projectName", label: "测评项目" }, // 字段配置
      roleCodes: ["student", "parent", "teacher", "other"], // 哪些角色可展示
      classCodes: ["evaluation"], // 哪些待办类型可展示
      types: ["done", "undone"] // 哪些待办状态可展示
    },
    {
      columnOp: { prop: "updatedAt", label: "测评完成时间" }, // 字段配置
      roleCodes: ["student", "parent", "teacher", "other"], // 哪些角色可展示
      classCodes: ["evaluation"], // 哪些待办类型可展示
      types: ["done"] // 哪些待办状态可展示
    }
  ];
  let columns = [];
  data.forEach(d => {
    // 按条件过滤，符合条件的才展示
    if (
      d["roleCodes"].includes(roleCode) &&
      d["classCodes"].includes(classCode) &&
      d["types"].includes(type)
    ) {
      columns.push(d["columnOp"]);
    }
  });
  return columns;
}

/**
 * 获取操作按钮的权限
 * @param userInfo
 * @param roleCode
 * @param calssCode 待办类型
 * @param doneType 完成状态
 * @returns {
 *  isEdit: true, // 是否可编辑
 *  isShow: true // 是否可显示
 * }
 */
export const getHandlePerm = function(userInfo, roleCode, calssCode, doneType) {
  let perm = {
    isEdit: false, // 是否可编辑
    isShow: false // 是否可显示
  };
  // 是否心理老师/心理专家（保护隐私，心理老师/心理专家才能查看学生测评报告与干预）
  let isXinli = (userInfo.postName || "").includes("心理");
  // 已完成
  if (doneType === "done") {
    // 是否心理老师/心理专家
    if (isXinli) {
      perm.isShow = true; // 可以查看测评或预警报告
    } else {
      perm.isShow = false; // 不能查看报告
    }
    perm.isEdit = false;
  } else {
    // 未完成
    // 测评类型
    if (calssCode === "evaluation") {
      let isPerm = roleCode === "student"; // 是学生
      perm.isShow = isPerm;
      perm.isEdit = isPerm;
    }
    // 预警类型
    else if (calssCode === "warn") {
      perm.isShow = isXinli;
      perm.isEdit = isXinli;
    }
    // 预约类型
    else if (calssCode === "reserve") {
      let isPerm = roleCode === "teacher"; // 是老师
      perm.isShow = isPerm;
      perm.isEdit = isPerm;
    }
  }
  return perm;
};
